#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define flushnone 1
#define flushline (1<<1)
#define flushall (1<<2)

typedef struct myFILE
{
    int _fileino;  //fd
    char _buff[1024];
    int _flushway;
    int _end;

}myFILE;


myFILE* myfopen(const char* path, const char* mode)
{
    
    int fd = 0;
    if(!strcmp(mode, "r"))
    {
        fd = open(path, O_RDONLY);
        if(fd<0)
        {
            perror("open");
            exit(1);
        }
    }
    else if(!strcmp(mode, "w"))
    {
        fd = open(path, O_RDONLY|O_CREAT|O_TRUNC,0666);
        if(fd<0)
        {
            perror("open");
            exit(1);
        }
    }
    else if(!strcmp(mode, "a"))
    {
        fd =open(path, O_RDONLY|O_CREAT|O_APPEND,0666);
        if(fd < 0)
        {
            perror("open");
            exit(1);
        }
    }
    else{ 
    }


    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(!fp)
    {
        perror("malloc");
        exit(1);
    }
    fp->_fileino = fd;

    return fp;

}


void myfflush(myFILE* stream)
{
    if(stream->_end)
    {
        write(stream->_fileino, stream->_buff, stream->_end);
        stream->_end = 0;
    }
    return;
}

int myclose(myFILE* stream)
{
    myfflush(stream);
    return close(stream->_fileino);
}


int mywrite(const char* s, int num, myFILE* stream)
{
    memcpy(stream->_buff + stream->_end, s, num);
    stream->_end += num;

    if(stream->_buff[stream->_end -1] == '\n' && stream->_flushway == flushline && stream->_end)
        myfflush(stream);

    return num;
}

